package com.zjwd.system.service.init;

import com.zjwd.common.constant.UserConstants;
import com.zjwd.common.core.domain.entity.SysRole;
import com.zjwd.common.utils.DateUtils;
import com.zjwd.common.utils.SecurityUtils;
import com.zjwd.common.utils.uuid.UUID;
import com.zjwd.system.domain.SysUserRole;
import com.zjwd.system.mapper.SysRoleMapper;
import com.zjwd.system.mapper.SysRoleMenuMapper;
import com.zjwd.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * 角色初始化服务
 *
 * @author liquan
 */
@Service
public class RoleInitializationService {

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 系统平台初始化默认角色
     * 包含：管理员，施工单位，监理单位，业主单位，劳务工角色
     *
     * @param platformCode 系统平台编号
     */
    @Transactional(rollbackFor = Exception.class)
    public void initializePlatformRoles(String platformCode) {
        // 查询出默认角色及其权限
        List<SysRole> defaultRoles = roleMapper.selectDefaultRoleList();
        // 2. 批量复制角色，重新排序从1开始
        List<SysRole> initRoles = new ArrayList<>();
        int roleSort = 1;
        for (SysRole defaultRole : defaultRoles) {
            SysRole copy = copyRoleForPlatform(defaultRole, platformCode, roleSort++);
            initRoles.add(copy);
        }
        // 3. 批量保存新角色
        roleMapper.batchRole(initRoles);
        // 4. 批量保存角色菜单关联
        for (SysRole role : initRoles) {
            if (role.getPermissions() != null && !role.getPermissions().isEmpty()) {
                roleMenuMapper.batchInsertRoleMenusByPermissions(role.getRoleId(), role.getPermissions());
            }
            // 当前登录用户和管理员设置关联
            if (UserConstants.DEFAULT_ROLE_ADMIN_NAME.equals(role.getRoleName())) {
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(role.getRoleId());
                userRole.setUserId(SecurityUtils.getUserId());
                List<SysUserRole> userRoles = new ArrayList<>();
                userRoles.add(userRole);
                userRoleMapper.batchUserRole(userRoles);
            }
        }
    }

    /**
     * 拷贝角色
     *
     * @param source 默认角色
     * @param platformCode 平台编号
     * @param roleSort 排序字段
     * @return 初始化角色
     */
    private SysRole copyRoleForPlatform(SysRole source, String platformCode, int roleSort ) {
        SysRole copy = new SysRole();
        copy.setPlatformCode(platformCode);
        // 重命名规则：移除"默认"前缀
        copy.setRoleName(source.getRoleName().replace("默认", ""));
        copy.setRoleKey(UUID.fastUUID().toString());
        copy.setRoleSort(roleSort);
        copy.setDataScope(source.getDataScope());
        copy.setMenuCheckStrictly(source.isMenuCheckStrictly());
        copy.setDeptCheckStrictly(source.isDeptCheckStrictly());
        copy.setStatus(source.getStatus());
        copy.setDelFlag(source.getDelFlag());
        copy.setCreateBy(SecurityUtils.getUsername());
        copy.setCreateTime(DateUtils.getNowDate());
        // 复制权限字符串集合
        if (source.getPermissions() != null) {
            copy.setPermissions(new HashSet<>(source.getPermissions()));
        }
        return copy;
    }

}
